package cn.wd.service;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import cn.wd.common.constant.DefaultValues;
import cn.wd.common.util.IdUtils;
import cn.wd.model.LoginInfo;
import cn.wd.model.ServiceException;
import cn.wd.util.CacheKey;
import cn.wd.util.RedisService;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import io.micrometer.common.util.StringUtils;
import jakarta.servlet.http.HttpServletRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;

import java.util.Collection;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * @author wangdong
 * @date 2024/10/11 11:54
 * @Description: token验证处理
 **/

@Service
public class TokenService {
    @Value("${token.header}")
    private String header;

    /** 令牌秘钥 */
    @Value("${token.secret}")
    private String secret;

    /** 令牌有效期（默认30分钟） */
    @Value("${token.expireTime}")
    private int expireTime;

    /** 令牌有效期（默认7天） */
    @Value("${token.expireTimeByApp}")
    private int expireTimeByApp;


    protected static final long MILLIS_SECOND = 1000;

    protected static final long MILLIS_MINUTE = 60 * MILLIS_SECOND;

    private static final Long MILLIS_MINUTE_TEN = 20 * 60 * 1000L;

    private final RedisService redisService;

    public TokenService(RedisService redisService) {
        this.redisService = redisService;
    }

    /**
     * 获取用户身份信息
     * @return 用户信息
     */
    public LoginInfo getLoginUser(HttpServletRequest request) {
        // 获取请求携带的令牌
        String jwtToken = getToken(request);
        if (StringUtils.isNotEmpty(jwtToken)) {
            try {
                Claims claims = parseToken(jwtToken);
                // 解析对应的权限以及用户信息
                String token = (String) claims.get(DefaultValues.LOGIN_USER_KEY);
                return JSONUtil.toBean((String) redisService.get(CacheKey.getTokenUserKey(token)), LoginInfo.class);
            }
            catch (Exception e) {
                throw new ServiceException("获取用户身份信息异常");
            }
        }
        return new LoginInfo();
    }

    /**
     * 设置用户身份信息
     */
    public void setLoginUser(LoginInfo loginUser) {
        if (loginUser != null && StringUtils.isNotEmpty(loginUser.getToken())) {
            refreshToken(loginUser);
        }
    }

    /**
     * 删除用户身份信息
     */
    public void delLoginUser(String token) {
        if (StringUtils.isNotEmpty(token)) {
            LoginInfo loginInfo = JSONUtil.toBean((String) redisService.get(CacheKey.getTokenUserKey(token)), LoginInfo.class);
            redisService.delete(CacheKey.getTokenKey(loginInfo.getUsername()));
            redisService.delete(CacheKey.getTokenUserKey(token));
        }
    }

    /**
     * 创建令牌
     */
    public String createToken(LoginInfo loginUser) {
        // 为了满足不同登录来源生成不同token，加了一个loginType；为了满足互斥登录，加了一个随机uuid
        String token = loginUser.getId() + ":" + IdUtils.fastUUID();

        loginUser.setToken(token);
        setUserAgent(loginUser);
        refreshTokenLogin(loginUser);

        Map<String, Object> claims = new HashMap<>(4);
        claims.put(DefaultValues.LOGIN_USER_KEY, token);
        return createToken(claims);
    }

    /**
     * 验证令牌有效期，相差不足20分钟，自动刷新缓存
     */
    public void verifyToken(LoginInfo loginUser) {
        long expireTime = loginUser.getExpireTime();
        long currentTime = System.currentTimeMillis();
        if (expireTime - currentTime <= MILLIS_MINUTE_TEN) {
            refreshToken(loginUser);
        }
    }

    /**
     * 刷新令牌有效期
     */
    public void refreshToken(LoginInfo loginUser) {
        loginUser.setLoginTime(System.currentTimeMillis());
        loginUser.setExpireTime(loginUser.getLoginTime() + expireTime * MILLIS_MINUTE);
        // 根据  前缀:loginType:userId:uuid  将loginUser缓存
        String userKey = CacheKey.getTokenUserKey((loginUser.getToken()));
        redisService.setEx(userKey, loginUser, expireTime, TimeUnit.MINUTES);
    }

    /**
     * 刷新令牌有效期 (登录时专用，用于判断是否互斥登录)
     */
    public void refreshTokenLogin(LoginInfo loginUser) {
        loginUser.setLoginTime(System.currentTimeMillis());
        loginUser.setExpireTime(loginUser.getLoginTime() + expireTime * MILLIS_MINUTE);
        // 根据 前缀:loginType:userId 将loginUser缓存
        String userKey = CacheKey.getTokenUserKey(loginUser.getToken());
        redisService.setEx(userKey, loginUser, expireTime, TimeUnit.MINUTES);
    }

    /**
     * 设置用户代理信息
     */
    public void setUserAgent(LoginInfo loginUser) {
        // UserAgent userAgent = UserAgent.parseUserAgentString(ServletUtils.getRequest().getHeader("User-Agent"));
        // String ip = IpUtils.getIpAddr(ServletUtils.getRequest());
        // loginUser.setIpaddr(ip);
        // loginUser.setLoginLocation(AddressUtils.getRealAddressByIP(ip));
        // loginUser.setBrowser(userAgent.getBrowser().getName());
        // loginUser.setOs(userAgent.getOperatingSystem().getName());
    }

    /**
     * 从数据声明生成令牌
     */
    private String createToken(Map<String, Object> claims) {
        return Jwts.builder()
                .setClaims(claims)
                .signWith(SignatureAlgorithm.HS512, secret).compact();
    }

    /**
     * 从令牌中获取数据声明
     */
    public Claims parseToken(String token) {
        return Jwts.parser()
                .setSigningKey(secret)
                .parseClaimsJws(token)
                .getBody();
    }

    /**
     * 从令牌中获取用户名
     */
    public String getUsernameFromToken(String token) {
        Claims claims = parseToken(token);
        return claims.getSubject();
    }

    /**
     * 获取请求token
     */
    public String getToken(HttpServletRequest request) {
        String token = request.getHeader(header);
        if (StrUtil.isNotBlank(token) && token.startsWith(DefaultValues.TOKEN_PREFIX)) {
            token = token.replace(DefaultValues.TOKEN_PREFIX, "");
        }
        return token;
    }
}
